package com.dhh.sky.widget;

import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.FrameLayout;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.dhh.sky.R;
import com.dhh.sky.activity.FileListActivity;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.service.DeleteOperationService;
import com.dhh.sky.service.DownloadOperationService;
import com.dhh.sky.service.RenameOperationService;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.OperationManager;

public class FileListActionMode implements ActionMode.Callback{
	public static final Long MODE_ALL = Long.valueOf(0);
	public static final Long MODE_FILE = Long.valueOf(1);
	public static final Long MODE_NONE = Long.valueOf(2);
	private FileListActivity context;
	protected OperationManager oManager;
	
	public FileListActionMode(FileListActivity context){
		this.context = context;
		oManager = new OperationManager(context);
	}

	@Override
	public boolean onCreateActionMode(ActionMode mode, Menu menu) {
		addDownloadAction(menu);
		addDeleteAction(menu);
		addCopyAction(menu);
		addMoveAction(menu);
		addRenameAction(menu);
		addShareAction(menu);
		
		return true;
	}

	@Override
	public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
		return false;
	}

	@Override
	public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
		return false;
	}

	@Override
	public void onDestroyActionMode(ActionMode mode) {		
		context.releaseMode();
	}
	
	private void addDownloadAction(Menu menu){
		MenuItem action = menu.add(context.getString(R.string.ab_download));
		action.setIcon(R.drawable.ic_download);
		action.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				if(!CUtil.isNetworkAvailable(context)){
					context.showToast(context.getString(R.string.msg_error_network_operation), false);
				}else{
					oManager.addDownloadOperation(context.getItemsNameSelected(),context.getCurrentPath());
					Intent intent = new Intent(context,DownloadOperationService.class);
					context.startService(intent); 
				}
				context.refreshItems();
				return true;
			}});
		action.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
	}

	private void addDeleteAction(Menu menu){
		MenuItem action = menu.add(context.getString(R.string.ab_delete));
		action.setIcon(R.drawable.ic_delete);
		action.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				if(!CUtil.isNetworkAvailable(context)){
					context.showToast(context.getString(R.string.msg_error_network_operation), false);
				}else{
					oManager.addDeleteOperation(context.getItemsNameSelected(),context.getCurrentPath());
					context.onProgressStatus(true);
					Intent intent = new Intent(context,DeleteOperationService.class);
					context.startService(intent); 
					context.hideSelectedItem();
					//context.refreshItems();
				}
				return true;
			}});
		action.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
	}
	
	private void addCopyAction(Menu menu){
		MenuItem action = menu.add(context.getString(R.string.ab_copy));
		action.setIcon(R.drawable.ic_copy);
		action.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				if(!CUtil.isNetworkAvailable(context)){
					context.showToast(context.getString(R.string.msg_error_network_operation), false);
				}else{
					FragmentManager fm = context.getSupportFragmentManager();
					FolderChooseDialog chooseDialog = new FolderChooseDialog(context);
					Bundle data = new Bundle();
					data.putStringArray(Constant.PARAM_ITEM_NAME, context.getItemsNameSelected());
					data.putString(Constant.PARAM_PATH, context.getCurrentPath());
					data.putInt(Constant.PARAM_REQUEST, Constant.REQ_OPERATION_COPY);
					chooseDialog.setArguments(data);
					chooseDialog.show(fm, context.getString(R.string.title_dialog_folder_choose));
					context.refreshItems();
				}
				return true;
			}});
		action.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
	}
	
	private void addMoveAction(Menu menu){
		MenuItem action = menu.add(context.getString(R.string.ab_cut));
		action.setIcon(R.drawable.ic_cut);
		action.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				if(!CUtil.isNetworkAvailable(context)){
					context.showToast(context.getString(R.string.msg_error_network_operation), false);
				}else{
					FragmentManager fm = context.getSupportFragmentManager();
					FolderChooseDialog chooseDialog = new FolderChooseDialog(context);
					Bundle data = new Bundle();
					data.putStringArray(Constant.PARAM_ITEM_NAME, context.getItemsNameSelected());
					data.putString(Constant.PARAM_PATH, context.getCurrentPath());
					data.putInt(Constant.PARAM_REQUEST, Constant.REQ_OPERATION_MOVE);
					chooseDialog.setArguments(data);
					chooseDialog.show(fm, context.getString(R.string.title_dialog_folder_choose));
					context.hideSelectedItem();
					context.refreshItems();
				}
				return true;
			}});
		action.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
	}
	
	private void addRenameAction(Menu menu){
		MenuItem action = menu.add(context.getString(R.string.ab_rename));
		action.setIcon(R.drawable.ic_edit);
		action.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				if(!CUtil.isNetworkAvailable(context)){
					context.showToast(context.getString(R.string.msg_error_network_operation), false);
				}else{
					final FrameLayout fl = new FrameLayout(context);
	                final EditText title = new EditText(context);
	                final SkyDriveObject file = context.getItemSeleted().get(0);
	                title.setText(file.getName());
	                fl.addView(title, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));   
	                title.setSingleLine(false);
	                title.setGravity(Gravity.TOP);
	                
	                             
	                AlertDialog.Builder builder = new AlertDialog.Builder(context);
	                //TODO replace from resource
	                builder.setView(fl).setTitle("File Rename");
	                builder.setPositiveButton(context.getString(R.string.label_ok), new DialogInterface.OnClickListener(){                     
		                @Override
		                public void onClick(DialogInterface d, int which) {  
		                        try {
			                        String name = title.getText().toString();
			                        file.setName(name);
			                        JSONObject body = new JSONObject();
									body.put("name", name);
			                        String path = context.getItemsNameSelected()[0];
			                        oManager.addRenameOperation(path,context.getCurrentPath(), body.toString());
			                        context.onProgressStatus(true);
			                        Intent intent = new Intent(context,RenameOperationService.class);
			                        context.startService(intent);
			        				context.refreshItems();
								} catch (Exception e) {
									Log.e(Constant.TAG, e.getMessage(), e);
								}
		                }
	                });
					builder.setNegativeButton(context.getString(R.string.label_cancel),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface d, int which) {
									context.refreshItems();
									d.dismiss();
								}
							});
	                
	                builder.create().show();
				}
				return true;
			}});
		action.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
	}
	
	private void addShareAction(Menu menu){
		MenuItem action = menu.add(context.getString(R.string.ab_share));
		action.setIcon(R.drawable.ic_share);
		action.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				String[] paths = context.getItemsNameSelected();
				if(paths!=null && paths.length>0){
					context.shareFile(paths[0]);
					context.refreshItems();
				}
				return true;
			}});
		action.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
	}
}
